using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceModel;
using System.Threading;
using MBWebService.Core;
using MBWebService.Core.Logging;
using MBWebService.Server.Proxy;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using MBWebService.Core.Client;
using MBWebService.Client.Code;

namespace MBWebService.Client
{
    public class MyAddIn : IAddInModule, IAddInEntryPoint
    {
        #region Private Members

        private EventWaitHandle m_waitHandle = new ManualResetEvent(false);
        private static string sessionName;
        private MCClient client;

        #endregion

        public void Initialize(Dictionary<string, object> appInfo, Dictionary<string, object> entryPointInfo)
        {
            try
            {
                // Sets the wait handle to the launch method will not exit
                m_waitHandle.Reset();
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage("Error initialising addin; ERROR: {0}", ex.Message);
                throw;
            }
        }

        public void Uninitialize()
        {
            try
            {
                //  Allow our launch method to exit
                m_waitHandle.Set();
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage("Error uninitialising addin; ERROR: {0}", ex.Message);
                throw;
            }
            finally
            {
                if (client != null)
                {
                    client.Unsubscribe();
                }
            }

        }

        public void Launch(AddInHost host)
        {
            //ShowDialog(host, "Attach to process now...", 15);
            AppSettings.Initialise();

            Logger.Instance.LogMessage("Attempting service start");
            try
            {
#if DEBUG
                ShowDialog(host, "Waiting for attach...", 10);
                // Thread.Sleep(TimeSpan.FromSeconds(10));
#endif

                MBWebService.Core.Classes.RemoteDevice serviceDevice = new Core.Classes.RemoteDevice
                {
                    DnsName = "localhost",
                    BasePort = AppSettings.UserSettings.BasePort
                };

                client = new MCClient(serviceDevice, GetDevice());
                client.ServiceStarted += (o, e) => { ShowDialogIfInSettings("Success loading MediaBrowser Web Service!", 2); };
                client.ServiceClosed += (o, e) => { ShowDialogIfInSettings("MBService disconnected", 2); };
                client.ConnectToService();

                m_waitHandle.WaitOne();

                if (host != null && host.ApplicationContext != null)
                {
                    host.ApplicationContext.SingleInstance = true;
                }

                Application app = new Application(host);
                app.Start();
                
                Logger.Instance.LogMessage("Plugin successfully loaded");
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage(ex.Message);
                throw;
            }
        }

        public static void ShowDialogIfInSettings(string strClickedText, int timeout)
        {
            if (AppSettings.UserSettings.ShowLoadSuccess)
            {
                if (AddInHost.Current != null)
                {
                    ShowDialog(AddInHost.Current, strClickedText, timeout);
                }
            }
        }

        public static void ShowDialog(AddInHost host, string strClickedText, int timeout)
        {
            bool modal = true;
            string caption = Resources.DialogCaption;

            if (host != null)
            {
                host.MediaCenterEnvironment.Dialog(strClickedText,
                                              caption,
                                              new object[] { DialogButtons.Ok },
                                              timeout,
                                              modal,
                                              null,
                                              delegate(DialogResult dialogResult) { });
            }
        }

        public PlaybackDevice GetDevice()
        {
            PlaybackDevice device = new PlaybackDevice
            {
                IsMediaCenter = !MediaBrowser.Application.RunningOnExtender,
                IsRemote = false,
                Name = AppSettings.SessionName
            };

            return device;
        }
    }
}